/// <reference path='../_all.ts' />

module PiiS {
    'use strict';

    /**
      *   The person controller for the app. The controller:
      *   - Creates new user.
      */
    export class PersonController {

        /**
          * This method is called on prototype during registration into IoC container. 
          * It provides $injector with information about dependencies to be injected into constructor
          * it is better to have it close to the constructor, because the parameters must match in count and type.
          */
        public injection(): any[] {
            return [
                '$scope',
                '$location',
                '$http',
                PersonController
            ]
        }

        /** Dependencies are injected via AngularJS $injector
          * controller's name is registered in App.ts and invoked from ng-controller attribute in index.html.
          */
        constructor
            (
            private $scope: IPersonScope,
            private $location: ng.ILocationService,
            private $http : ng.IHttpService
            )
        {
            //Initializing variables.
            $scope.personDescription = '';
            $scope.registeredUsers = 0;
            $scope.votesCast = 0;


            // Adding event handlers to the scope, so they could be bound from view/HTML
            // these lambdas fix this keyword in JS world.
            $scope.createPerson = () => this.createPerson();

            this.loadCount();
        }

        /**
          * Contacts the remote server to create new Person instance.
          */
        createPerson(): void {
            this.$scope.loading = true;
            this.$http.post('/api/Person', new Person(0, this.$scope.personDescription))
                .success((result: Person, status, headers) => {
                    this.$scope.loading = false;
                    this.$location.path("/movies/" + result.Id);
                })
                .error((result, status, headers) => {
                    console.log("Error while creating person object.");
                });
        }

        loadCount(): void {
            this.$http.get('/api/Person')
                .success((result, status, headers) => {
                    this.$scope.registeredUsers = result.m_Item1;
                    this.$scope.votesCast = result.m_Item2;
                }).error((result, status, headers) => {
                    console.log("Error while loading person and votes count.");
                });
            setTimeout(() => {
                this.loadCount();
            }, 10000);
        }
    }
}